import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store/index';

import Login from '../views/login.vue';
import Register from '../views/register.vue';
import Layout from '../views/layout.vue';
import Index from '../views/index.vue';
import ProductList from '../views/productList.vue';
import AddProduct from '../views/addProduct.vue';
import NotFound from '../views/notFound.vue';
import UserInfo from '../views/userInfo.vue';
import MyLibrary from '../views/myLibrary.vue';

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      outOfLayout: true,
      title:'登录'
    }
  }, {
    path: '/register',
    name: 'register',
    component: Register,
    meta: {
      outOfLayout: true,
      title:'注册'
    }
  }, {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/index',
    meta: {
      title:''
    },
    children: [
      {
        path: '/index',
        name: 'index',
        component: Index,
        meta: {
          title:'首页'
        }
      }, {
        path: '/product-list',
        name: 'product-list',
        component: ProductList,
        meta: {
          title:'商品列表'
        }
      }, {
        path: '/add-product',
        name: 'add-product',
        component: AddProduct,
        meta: {
          title:'添加商品'
        }
      }, {
        path: '/user-info',
        name: 'user-info',
        component: UserInfo,
        meta: {
          title:'用户信息'
        }
      }, {
        path: '/my-library',
        name: 'my-library',
        component: MyLibrary,
        meta: {
          title:'我的素材'
        }
      }
    ]
  }, {
    path: '*',
    name: 'not-found',
    component: NotFound
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 登录状态路由拦截器
router.beforeEach((to, from, next) => {
  let isAuthenticated = localStorage.getItem('userInfo');
  if (!to.meta.outOfLayout && !isAuthenticated) next({ name: 'login' })
  else {
    store.commit('changeRouter',to.meta.title);
    next()
  }
})

export default router
